package com.hjm.system.service.question.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.hjm.common.core.constants.Constants;
import com.hjm.common.core.enums.ResultCode;
import com.hjm.redis.service.RedisService;
import com.hjm.security.exception.ServiceException;
import com.hjm.system.domain.question.Question;
import com.hjm.system.domain.question.es.QuestionES;
import com.hjm.system.domain.question.dto.QuestionAddDTO;
import com.hjm.system.domain.question.dto.QuestionEditDTO;
import com.hjm.system.domain.question.dto.QuestionQueryDTO;
import com.hjm.system.domain.question.vo.QuestionDetailVO;
import com.hjm.system.domain.question.vo.QuestionVO;
import com.hjm.system.elasticsearch.QuestionRepository;
import com.hjm.system.manage.QuestionCacheManager;
import com.hjm.system.mapper.exam.ExamQuestionMapper;
import com.hjm.system.mapper.question.QuestionMapper;
import com.hjm.system.service.question.QuestionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    ExamQuestionMapper examQuestionMapper;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private RedisService redisService;
    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {
        // 这里是 竞赛题目的列表
        String excludeIdStr = questionQueryDTO.getExcludeStr();
        if(StrUtil.isNotBlank(excludeIdStr)){
            String[] excludeIdArr = excludeIdStr.split(Constants.SPLIT_SEM);
            // 类型转换
            Set<Long> excludeIdSet = Arrays.stream(excludeIdArr).
                    map(Long::valueOf).
                    collect(Collectors.toSet());
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }
//        List<QuestionVO> questionList = questionMapper.selectQuestionList(questionDTO);
////        if(questionList == null  || questionList.isEmpty() ){
//        if(CollectionUtil.isEmpty(questionList)){
//            return TableDataInfo.empty();
//        }
//        return TableDataInfo.success(questionList,questionList.size()); // 这里存在错误，应当传入总数，而非符合条件总数

        //        使用分页插件 来实现分页功能，下面是 设置 pagenum和pagesize 来进行查询
        PageHelper.startPage(questionQueryDTO.getPageNum(),
                questionQueryDTO.getPageSize());
        // 这里仅仅是 根据 questionQueryDTO 中 title 和 difficulty 的 值进行查询

        return questionMapper.selectQuestionList(questionQueryDTO);
    }

    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {
        // 判断添加的题目是否已经存在

        Question quest = questionMapper.selectOne(new LambdaQueryWrapper<Question>().select().eq(Question::getTitle, questionAddDTO.getTitle()));

        if(quest != null){
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }

        Question question = new Question();

        // 这个是复制方法
        BeanUtils.copyProperties(questionAddDTO, question);

        int insert = questionMapper.insert(question);
        if(insert <= 0){
            return false;
        }
        // 插入数据库成功 后 需要加入 es 中
        QuestionES questionES = new QuestionES();
        BeanUtils.copyProperties(question, questionES);
        questionRepository.save(questionES);

        questionCacheManager.addCache(questionES.getQuestionId());

        return true;
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {

        Question question = questionMapper.selectById(questionId);
        if(question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS );
        }
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        BeanUtils.copyProperties(question, questionDetailVO);

        return questionDetailVO;
    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        List<Question> check = questionMapper.selectList(new LambdaQueryWrapper<Question>().
                eq(Question::getTitle, questionEditDTO.getTitle()));
        if(check.size() >=2 ){
            throw new ServiceException(ResultCode.FAILED_QUESTION_IS_EXISTS);
        }
        Question question = questionMapper.selectById(questionEditDTO.getQuestionId());
        if(question == null) {
            throw new ServiceException(ResultCode.FAILED_QUESTION_IS_EXISTS);
        }

        BeanUtils.copyProperties(questionEditDTO, question);
//        question.setTitle(questionEditDTO.getTitle());
//        question.setContent(questionEditDTO.getContent());
//        question.setDifficulty(questionEditDTO.getDifficulty());
//        question.setSpaceLimit(questionEditDTO.getSpaceLimit());
//        question.setTimeLimit(questionEditDTO.getTimeLimit());
//        question.setDefaultCode(questionEditDTO.getDefaultCode());
//        question.setMainFunc(questionEditDTO.getMainFunc());
//        question.setQuestionCase(questionEditDTO.getQuestionCase());

        QuestionES questionES = new QuestionES();
        BeanUtils.copyProperties(question, questionES);
        questionRepository.save(questionES);

        return questionMapper.updateById(question);
    }

    @Override
    public int delete(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if(question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }

        //todo 还需要删除 竞赛题目中的 题目
//        int deleteEQ = examQuestionMapper.delete(new LambdaQueryWrapper<ExamQuestion>()
//                .eq(ExamQuestion::getQuestionId, questionId));

        questionRepository.deleteById(questionId);

        questionCacheManager.deleteCache(questionId);

        return  questionMapper.deleteById(questionId);

    }
}
